<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNew ? '登记事项' : '修改事项'"
    width="70%"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-scrollbar ref="scrollbarRef" max-height="60vh" v-loading="loading">
      <el-form
        ref="formRef"
        class="mr-3"
        :model="formData"
        scroll-to-error
        label-width="90px"
        :rules="rules"
      >
        <el-form-item label="事项标题" prop="matterTitle">
          <el-input
            v-model="formData.matterTitle"
            show-word-limit
            :maxlength="200"
            :disabled="disabled"
          />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="责任领导" prop="responsibleLeader">
              <LeaderSelect
                v-model="formData.responsibleLeader"
                :disabled="disabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务领域" prop="domainId">
              <DictionarySelect
                v-model="formData.domainId"
                :disabled="disabled"
                parent-dictionary-value="runway"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重点关注" prop="isFocus">
              <FocusSelect v-model="formData.isFocus" :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="办理要求" prop="handleRequire">
          <el-input
            v-model="formData.handleRequire"
            type="textarea"
            :disabled="disabled"
            :autosize="{ minRows: 5 }"
          />
        </el-form-item>
        <el-form-item label="牵头单位" prop="unitId">
          <unit-select v-model="formData.unitId" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="期限设置" prop="matterDeadlinesList">
          <DeadlineTable
            v-model="formData.matterDeadlinesList"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="抄送单位" prop="copyUnit">
          <CopyUnitTable v-model="formData.copyUnit" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="相关材料" prop="uuid">
          <file-upload
            ref="fileUploadRef"
            v-model="formData.fileList"
            :disabled="disabled"
          />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer flex justify-between items-center">
        <div>
          <el-button
            v-if="formData.id && !canChange"
            type="primary"
            :disabled="
              taskStatus === ETaskStatus['审批中'] ||
              taskStatus === ETaskStatus['通过']
            "
            @click="canChange = true"
          >
            编辑
          </el-button>
        </div>
        <div>
          <el-button @click="close">取消</el-button>
          <el-button
            v-if="!disabled"
            type="primary"
            @click="submit"
            :loading="loading"
          >
            提交
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, useTemplateRef } from 'vue'
import { FormInstance, FormRules, ScrollbarInstance } from 'element-plus'
import DictionarySelect from '@/components/dictionary/DictionarySelect.vue'
import LeaderSelect from '@/components/leader/LeaderSelect.vue'
import DeadlineTable from '@/views/mission/task/thing/DeadlineTable.vue'
import UnitSelect from '@/components/unit/UnitSelect.vue'
import FileUpload from '@/components/FileUpload.vue'
import CopyUnitTable from '@/views/mission/task/thing/CopyUnitTable.vue'
import { InternalRuleItem, Value } from 'async-validator/dist-types/interface'
import { addMatter, modifyMatter } from '@/api/mission/task'
import { getDeadlinesByMatterId, getMatterDetail } from '@/api/mission/thing'
import { getFileIdStr, initIFileList } from '@/plugins/file'
import FocusSelect from '@/components/statusShow/focus/FocusSelect.vue'
import { ETaskStatus } from '@/components/statusShow/util'

const { taskId, taskStatus } = defineProps<{
  taskStatus?: number
  taskId?: number | null | undefined
}>()

const emit = defineEmits(['update', 'add', 'refresh'])
const scrollbarRef = useTemplateRef<ScrollbarInstance>('scrollbarRef')
const formRef = useTemplateRef<FormInstance>('formRef')
const fileUploadRef =
  useTemplateRef<InstanceType<typeof FileUpload>>('fileUploadRef')

const dialogVisible = ref(false)
const isNew = ref(true)
const loading = ref(false)
const rowIndex = ref(null)
const canChange = ref(true)

const disabled = computed(() => {
  return !canChange.value
})

const formData = reactive({
  id: null,
  matterTitle: null,
  domainId: null,
  responsibleLeader: null,
  isFocus: 0,
  handleRequire: null,
  unitId: null,
  copyUnit: null,
  fileList: null,
  matterDeadlinesList: [],
})

const rules = ref<FormRules<typeof formData>>({
  matterTitle: { required: true, message: '请输入事项标题', trigger: 'blur' },
  responsibleLeader: {
    required: true,
    message: '请选择责任领导',
    trigger: 'change',
  },
  domainId: { required: true, message: '请选择业务领域', trigger: 'change' },
  unitId: {
    required: true,
    message: '请选择牵头单位',
    trigger: 'change',
  },
  matterDeadlinesList: {
    required: true,
    validator: validatorMatterDeadlinesList,
    trigger: 'noTrigger',
  },
})

function validatorMatterDeadlinesList(
  rule: InternalRuleItem,
  value: Value,
  callback: (error?: string | Error) => void,
) {
  if (Array.isArray(value) && value.length > 0) {
    const set = new Set()
    for (const item of value) {
      if (set.has(item.deadlineDate)) {
        return callback(new Error('事项期限不能重复'))
      } else {
        set.add(item.deadlineDate)
      }
    }
    return callback()
  } else {
    return callback(new Error('请添加事项期限'))
  }
}

function close() {
  dialogVisible.value = false
  loading.value = false
  isNew.value = true
  rowIndex.value = null
  canChange.value = true
  formRef.value.resetFields()
  Object.assign(formData, {
    id: null,
    matterTitle: null,
    domainId: null,
    responsibleLeader: null,
    isFocus: 0,
    handleRequire: null,
    unitId: null,
    copyUnit: null,
    fileList: null,
    matterDeadlinesList: [],
  })
  fileUploadRef.value.clearFileList()
  scrollbarRef.value.setScrollTop(0)
}

defineExpose({ show })

async function show(row?: number | any, index?: number) {
  dialogVisible.value = true
  if (row) {
    isNew.value = false
    if (typeof row !== 'number') {
      Object.assign(formData, {
        id: row.id,
        matterTitle: row.matterTitle,
        domainId: row.domainId,
        responsibleLeader: row.responsibleLeader,
        isFocus: row.isFocus,
        handleRequire: row.handleRequire,
        unitId: row.unitId,
        copyUnit: row.ccUnitIds
          ? row.ccUnitIds?.split(',').map((item: string) => Number(item))
          : null,
        fileList: initIFileList(row.fileList),
        fileIds: row.fileIds,
      })
      formData.matterDeadlinesList = row.matterDeadlinesList
      rowIndex.value = index
    } else {
      loading.value = true
      canChange.value = false
      const { data } = await getMatterDetail(row)
      if (data.status === 200) {
        Object.assign(formData, {
          id: data.data.matterId,
          matterTitle: data.data.matterTitle,
          domainId: data.data.domainId,
          responsibleLeader: data.data.responsibleLeader,
          isFocus: data.data.isFocus,
          handleRequire: data.data.handleRequire,
          unitId: data.data.leadUnitId,
          copyUnit: data.data.ccUnitIds
            ? data.data.ccUnitIds
                ?.split(',')
                .map((item: string) => Number(item))
            : null,
          fileList: initIFileList(data.data.fileList),
          fileIds: data.data.fileIds,
        })

        if (taskId && formData.id) {
          loading.value = true
          await getDeadlineList()
          loading.value = false
        } else {
          formData.matterDeadlinesList = data.data.matterDeadlinesList
        }
      }
      loading.value = false
    }
  }
}

async function getDeadlineList() {
  const { data } = await getDeadlinesByMatterId(formData.id)
  if (data.status === 200) {
    formData.matterDeadlinesList = data.data
  }
}

function submit() {
  formRef.value.validate(async (bool) => {
    if (!bool) {
      return
    }
    const postData = {
      taskId: taskId,
      id: formData.id,
      matterTitle: formData.matterTitle,
      domainId: formData.domainId,
      responsibleLeader: formData.responsibleLeader,
      isFocus: formData.isFocus,
      handleRequire: formData.handleRequire,
      unitId: formData.unitId,
      ccUnitIds: formData.copyUnit?.join() || '',
      fileIds: getFileIdStr(formData.fileList),
      fileList: null,
      matterDeadlinesList: formData.matterDeadlinesList,
    }

    if (taskId) {
      if (formData.id) {
        const { data } = await modifyMatter(postData)
        if (data.status === 200) {
          emit('refresh')
          close()
        }
      } else {
        const { data } = await addMatter(postData)
        if (data.status === 200) {
          emit('refresh')
          close()
        }
      }
    } else {
      postData.fileList = initIFileList(formData.fileList)
      if (rowIndex.value !== null) {
        emit('update', postData, rowIndex.value)
        close()
      } else {
        emit('add', postData)
        close()
      }
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.el-date-editor) {
  width: 100%;
}
</style>
